import javax.swing.*;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.*;
import java.util.Vector;


class SearchDialog extends JDialog {

    JCheckBox [] boxes;
    JTextField [] texts;
    JLabel [] labels;
    JCheckBox chkAwardsOnly;
    JCheckBox chkIgnorePrevious;

    Container contentpane;
    JButton btnSearch;
    String username,
           password,
           databaseName;

    JPanel resultsPanel;
    UserInterface ui;

    SearchDialog(UserInterface userint, String user, String pass, String dateName){
        ui=userint;
        username = user;
        password = pass;
        databaseName = dateName;

        contentpane = getContentPane();
        contentpane.setLayout(new BoxLayout(contentpane,BoxLayout.X_AXIS));
        setupComponents();


        setSize(900,600);
        setVisible(true);
    }

    public void setupComponents(){
        //0 keywords
        //1 actor
        //2 director
        //3 year
        //4 genre

        JPanel mainPanel = new JPanel();
        resultsPanel = new JPanel();
        GroupLayout layout = new GroupLayout(mainPanel);
        mainPanel.setLayout(layout);

        JLabel lblSearchby = new JLabel("Search:");
        lblSearchby.setFont(new Font("SERIF",Font.PLAIN,16));
        btnSearch = new JButton("Search");
        btnSearch.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e){
                            searchClicked(e);
                        }
                      });


        boxes = new JCheckBox[5];
        texts = new JTextField[5];
        labels = new JLabel[5];

        for(int i=0;i<5;i++){
            boxes[i] = new JCheckBox();
            texts[i] = new JTextField(15);
            labels[i] = new JLabel();
        }
        JLabel lblPrevious = new JLabel("Ignore Previously Rented");
        JLabel lblAward = new JLabel("Award Winners Only");
        chkIgnorePrevious = new JCheckBox();
        chkAwardsOnly = new JCheckBox();


        labels[0].setText("Keywords");
        labels[1].setText("Actor");
        labels[2].setText("Director");
        labels[3].setText("Year");
        labels[4].setText("Genre");

        layout.setHorizontalGroup(
           layout.createSequentialGroup()
              .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING,false)
                   .addComponent(lblSearchby)
                   .addComponent(boxes[0])
                   .addComponent(boxes[1])
                   .addComponent(boxes[2])
                   .addComponent(boxes[3])
                   .addComponent(boxes[4])
                   .addComponent(chkIgnorePrevious)
                   .addComponent(chkAwardsOnly)
                   .addComponent(btnSearch))
              .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING,false)
                   .addComponent(labels[0])
                   .addComponent(labels[1])
                   .addComponent(labels[2])
                   .addComponent(labels[3])
                   .addComponent(labels[4])
                   .addComponent(lblPrevious)
                   .addComponent(lblAward))
              .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING,false)
                   .addComponent(texts[0])
                   .addComponent(texts[1])
                   .addComponent(texts[2])
                   .addComponent(texts[3])
                   .addComponent(texts[4]))

                   );
        layout.setVerticalGroup(
           layout.createSequentialGroup()
              .addComponent(lblSearchby)
              .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                   .addComponent(boxes[0])
                   .addComponent(labels[0])
                   .addComponent(texts[0]))
              .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(boxes[1])
                    .addComponent(labels[1])
                    .addComponent(texts[1]))
              .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                   .addComponent(boxes[2])
                   .addComponent(labels[2])
                   .addComponent(texts[2]))
              .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                   .addComponent(boxes[3])
                   .addComponent(labels[3])
                   .addComponent(texts[3]))
              .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                   .addComponent(boxes[4])
                   .addComponent(labels[4])
                   .addComponent(texts[4]))
              .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                   .addComponent(chkIgnorePrevious)
                   .addComponent(lblPrevious))
              .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                   .addComponent(chkAwardsOnly)
                   .addComponent(lblAward))
              .addComponent(btnSearch)
                );

        contentpane.add(mainPanel);
        contentpane.add(resultsPanel);
    }


    public void searchClicked(ActionEvent e){
        Vector<String> args = new Vector<String>();
        String sqlStatement;
        StringBuffer sb = new StringBuffer();
        boolean sendStatement = false;

try{
        for(int h=0;h<5;h++){
            texts[h].setText(texts[h].getText().trim());
        }


        sqlStatement = new String("Select title, releasedate From Movies Where ");

        if(boxes[0].isSelected() && !(texts[0].getText().isEmpty()) ){

            String [] fields = texts[0].getText().trim().split(" ");

            sb.append("Movies.Title Like '%" + fields[0] + "%'");
            for(int i=1;i<fields.length;i++){
                sb.append(" OR Movies.Title LIKE '%" + fields[i] + "%'");
            }
            args.addElement(sb.toString());

        }

        if(boxes[2].isSelected() && !(texts[2].getText().isEmpty())){

            sb = new StringBuffer();
            sb.append("Movies.Director ='" + texts[2].getText() + "'");
            args.addElement(sb.toString());
        }
        if(boxes[3].isSelected() && !(texts[3].getText().isEmpty())){

            sb = new StringBuffer();
            sb.append("Movies.releasedate = "+ texts[3].getText());
            args.addElement(sb.toString());
        }
        if(boxes[4].isSelected() && !(texts[4].getText().isEmpty())){

            sb = new StringBuffer();
            sb.append("Movies.Genre ='" + texts[4].getText().toLowerCase() + "'");
            args.addElement(sb.toString());
        }

        sb = new StringBuffer();

        if(args.size()>1){
            sb.append(args.get(0));
            for(int i=1;i<args.size();i++){
                sb.append(" AND " + args.get(i));
            }

        } else if (args.size()==1){
            sb.append(args.get(0));

        }else if (args.size() == 0 && !(texts[1].getText().isEmpty())){
            System.out.println("no arguements for Where segment");
            return;
        }
        // AT THIS POINT IF NOTHING IS SELECTED THE CODE RETURNS
        // OTHERWISE ALL OTHER FIELDS ARE COMPILED INTO A SINGLE STATEMENT sqlSTATEMENT

        sqlStatement = sqlStatement + sb.toString();
        StringBuffer strActor = new StringBuffer();


        if(boxes[1].isSelected() && !(texts[1].getText().isEmpty())){

            String [] actorName = texts[1].getText().split(" ");
            for(int g=0;g<actorName.length;g++){
                actorName[g].trim();
            }
            strActor.append(
              "Select M.title, M.releasedate FROM (" +
                    "Select A.actorid from Actors A ");

            strActor.append("WHERE A.actorfirstname = '" + actorName[0] + "' OR A.actorLastName = '" + actorName[0] + "'");
            for(int g=1;g<actorName.length;g++){
                strActor.append(" OR A.actorfirstname = '" + actorName[g] + "' OR A.actorLastName = '" + actorName[g] + "'");

            }
            strActor.append( ") A2 Cross Join MovieActors M Where A2.actorid = m.actorid ");
        }
        //IF ACTOR IS ONLY ONE SELECTED
        if(args.size() ==0){
           sqlStatement = strActor.toString();

        }else if (args.size()>1 && boxes[1].isSelected()){ //MORE THAN ONE FIELD SELECTED  must add the statements
            sqlStatement = ("Select * From ( " +
                sqlStatement + ") Intersect (" + strActor.toString() + ")");

        }//otherwise the sqlSTATEMENT is already built and doesn't need modification

        if(chkAwardsOnly.isSelected()){
            StringBuffer strAward = new StringBuffer();
            sqlStatement = "(" + sqlStatement + ")" +
                "Intersect Select title,releasedate from MovieAwards";

        }
        //////HEY HEY HEY --FIX THIS BY REMOVING THE JOPTIONPANE INPUT DIALOG
        if(chkIgnorePrevious.isSelected()){
            sqlStatement = "(" + sqlStatement + ")" +
                " Except (select title,releasedate from history where mship# = ";

            String mship = ui.getMShip();
            sqlStatement = sqlStatement + mship + ")";

        }


        System.out.println(sqlStatement);

        DBQTable dbq = new DBQTable(databaseName);
        JScrollPane scroll;
        resultsPanel.removeAll();

            try{
                JTable table = dbq.getTable(username, password, sqlStatement);
                scroll = new JScrollPane(table);
                resultsPanel.add(scroll);
                resultsPanel.setSize(table.getSize());

                contentpane.validate();      //necessary to refresh the UI after adding the table;
            }catch (Exception x){
                System.out.println("Invalid SQL Statement");
                //x.printStackTrace();
            }

}catch(Exception x){
    System.out.println("Something Krazy 'Appened");
}
    }

}
